<?php
/*
 * Author: top-songshijie
 * Email :997031758@qq.com
 * DateTime: 2023/04/06 11:19
 */

namespace SSJ\LaravelHelper\Middleware;

use Closure;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use SSJ\LaravelHelper\Exceptions\TooManyRequests;

class PreventShakeMiddleware
{
    protected $prefix = 'preventshake::';

    /**
     * 总处理
     *
     * @param         $request
     * @param Closure $next
     * @param string  $flag 自定义防抖标识
     *
     * @return mixed
     * @throws TooManyRequests
     */
    public function handle($request, Closure $next, $flag = '')
    {
        $flag      = $flag ?: $this->getFlag($request);
        $cache_key = md5($this->prefix . $request->fullUrl() . $flag);
        $content   = Cache::get($cache_key);

        if ($content && $content === true) {
            throw new TooManyRequests('点击频率过快，请刷新重试');
        }

        if ($content) {
            $response = $next($request);
            $response->setContent($content);
            return $response;
        }

        $ttl = 3;
        Cache::put($cache_key, true, Carbon::now()->addSeconds($ttl));
        $response = $next($request);
        Cache::put($cache_key, json_encode($response->getOriginalContent()), Carbon::now()->addSeconds($ttl));

        return $response;
    }

    /**
     * 防抖标识
     *
     * @return string
     */
    protected function getFlag($request)
    {
        return $request->ip();
    }
}
